package com.kunlun.basedata.resource.service.impl;

import com.kunlun.basedata.resource.dao.ISystemLinkDao;
import com.kunlun.basedata.resource.model.SystemLinkModel;
import com.kunlun.basedata.resource.service.ISystemLinkService;
import com.kunlun.common.utils.CommonUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class SystemLinkService implements ISystemLinkService {

    @Autowired
    private ISystemLinkDao systemLinkDao;

    @Override
    public Map<String, List<SystemLinkModel>> getAllLinks(String dataType, String linkName) throws Exception {
        List<SystemLinkModel> links = systemLinkDao.getAllLinks(dataType, linkName);
        Map<String, List<SystemLinkModel>> resultMap = null;
        if (StringUtils.isNotEmpty(dataType)) {
            resultMap = new HashMap<>();
            resultMap.put(dataType, links);
        } else {
            resultMap = links.stream().collect(Collectors.groupingBy(SystemLinkModel::getType));
        }
        return resultMap;
    }

    @Override
    public void onAddLink(SystemLinkModel linkModel) throws Exception {
        if (StringUtils.isEmpty(linkModel.getId())) {
            linkModel.setId(CommonUtil.generateUUID());
            systemLinkDao.onAddLink(linkModel);
        } else {
            systemLinkDao.onUpdateLink(linkModel);
        }
    }

    @Override
    public void onDelete(String id) throws Exception {
        systemLinkDao.onDelete(id);
    }
}
